package com.cdc.taskhandler;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.lang.ref.WeakReference;

public class HandlerPostActivity extends AppCompatActivity {

    private TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_post);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                DownThread downThread=new DownThread();
                downThread.start();

                tvResult.setText("下载开始");
                Snackbar.make(view, "下载开始", Snackbar.LENGTH_LONG)
                       .setAction("Action", null).show();

            }
        });

        tvResult=findViewById(R.id.tvResult);
    }

    private  MyHandler myHandler=new MyHandler(HandlerPostActivity.this);
    private static class  MyHandler extends  Handler{
        private WeakReference<Context> reference;
        public MyHandler(Context context){
            reference=new WeakReference<Context>(context);
        }
        @Override
        public void handleMessage(Message msg) {
            HandlerPostActivity activity= (HandlerPostActivity) reference.get();
            if(activity!=null){

            }
        }
    };

    private  class DownThread extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                Runnable runnable=new Runnable() {
                    @Override
                    public void run() {
                        tvResult.setText("下载完成");
                    }
                };
                myHandler.post(runnable);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }



}
